package com.shanjupay.transaction.message;

import com.alibaba.fastjson.JSON;
import com.shanjupay.paymentagent.api.dto.PaymentResponseDTO;
import com.shanjupay.paymentagent.api.dto.TradeStatus;
import com.shanjupay.transaction.api.TransactionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @className: TransactionPayConsumer
 * @Description: TODO
 * @author: Huangjianyun
 * @date: 2021/10/28 16:03
 */
@Component
@RocketMQMessageListener(topic = "TP_PAYMENT_RESULT",consumerGroup = "CID_ORDER_CONSUMER")
@Slf4j
public class TransactionPayConsumer implements RocketMQListener<MessageExt> {
    @Resource
    TransactionService transactionService;


    @Override
    public void onMessage(MessageExt messageExt) {
        //获取消息的字节数据
        byte[] body = messageExt.getBody();
        //2将消息的字节数组进行转换成字符串
        String jsonString = new String(body);
        //将json串的消息进行解析成对应消息对象
        PaymentResponseDTO responseDTO = JSON.parseObject(jsonString, PaymentResponseDTO.class);
        //从消息里面获取订单号 第三方接口订单号，订单状态
        String tradeNo = responseDTO.getTradeNo(); //第三方接口订单号
        String outTradeNo = responseDTO.getOutTradeNo();
        TradeStatus tradeState = responseDTO.getTradeState();
        switch (tradeState){
            //成功
            case SUCCESS:
                transactionService.updateOrderTradeNoAndTradeState(outTradeNo,tradeNo,"2");
                return ;
            case REVOKED:
                transactionService.updateOrderTradeNoAndTradeState(outTradeNo,tradeNo,"4");
                return ;
            case FAILED:
                transactionService.updateOrderTradeNoAndTradeState(outTradeNo,tradeNo,"5");
                return ;
            default:
                throw new RuntimeException(String.format("无法解析支付结果:%s",body));

        }
    }
}
